package com.dldata.devtools30.controller.sysform;

import com.dldata.devtools30.entity.DevtFormMetadataEntity;
import com.dldata.devtools30.entity.DevtModelMetadataTableEntity;
import com.dldata.devtools30.repository.sysform.DevtFormMetadataDao;
import com.dldata.devtools30.service.metadata.DevtModelMetadataTableService;
import com.dldata.devtools30.utils.Result;
import com.dldata.devtools30.utils.StringUtil;
import com.google.common.collect.Lists;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/DevtFormMetadataController")
public class DevtFormMetadataController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    DevtFormMetadataDao sysCrfFormMetadataDao;
    @Autowired
    DevtModelMetadataTableService metadataTableService;

    @RequestMapping(value = "toSelPage")
    public String toEdit(String pid, HttpServletRequest request, HttpServletResponse response, Model model) throws  Exception{

        return "thymeleaf/devtools30/sysform/v_SelectMedataTable";
    }


    @RequestMapping(value = "/getAll")//46d614f9-f79b-459c-97bf-4053d8b06730
    @ResponseBody
    public Result getAll(HttpServletRequest request, HttpServletResponse response, Model model, @RequestParam Map<String, Object> param) {

        List<DevtFormMetadataEntity> crfFormMetadataEntityList= Lists.newArrayList(sysCrfFormMetadataDao.findAll());
        List<DevtModelMetadataTableEntity> tableEntities= metadataTableService.getAll();
        List<Map<String,Object>> mapList = new ArrayList<>();
        crfFormMetadataEntityList.stream().filter(w->{
            boolean templeid = w.getTempleid().equals(param.getOrDefault("templeid", ""));
            return templeid;
         }
        ).forEach(m->{
                    Map<String,Object> data=new HashMap<>();
                    data.put("id",m.getId());
                    data.put("name","");
                    data.put("code","");
                    data.put("tableid","");
                    data.put("tabletype","");
                    tableEntities.stream().filter(w->w.getId().equals(m.getTableid())).forEach(tm->{
                        data.put("tableid",m.getTableid());
                        data.put("tabletype",m.getTabletype());
                        data.put("name",tm.getName());
                        data.put("code",tm.getCode());
                    });
                    mapList.add(data);
                });
        return Result.ok(mapList);
    }
    @RequestMapping(value = "save")
    @ResponseBody
    public Result save(DevtFormMetadataEntity entity, HttpServletRequest request, HttpServletResponse response) throws  Exception{

        String result;
        try {
            if (entity.getId()==null||entity.getId().equals("")) {
                entity.setId(UUID.randomUUID().toString());
            }
            if(StringUtil.isEmptyOrLength0(entity.getTableid()) ||StringUtil.isEmptyOrLength0(entity.getTempleid())){
                return Result.error("参数有误");
            }
            if(Lists.newArrayList(sysCrfFormMetadataDao.findAll()).stream().filter(w->w.getTempleid().equals(entity.getTempleid())
            &&w.getTableid().equals(entity.getTableid())).count()>0){
                return Result.error("已经添加过了，不能重复添加");
            }
//            sysCrfFormMetadataDao.save(entity.getId(),entity);
            sysCrfFormMetadataDao.save(entity);

            return Result.ok();

        } catch (Exception ex) {

            logger.error("【执行" + this.getClass().getName() + ".save() 方法失败 】异常：" + ex.getMessage());
            return Result.error("操作错误，请稍候再试！");
        }

    }

    @RequestMapping("delete")
    @ResponseBody
    public Result delete(String id,HttpServletRequest request, HttpServletResponse response) throws Exception{
        String result;

        try {
            sysCrfFormMetadataDao.deleteById(id);

            return Result.ok();
        }
        catch (Exception ex){
            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage());
            return Result.error("操作错误，请稍候再试！");
        }

    }
    
    
    @RequestMapping(value = "/setParentTable")
    @ResponseBody
    public Result setParentTable(String id,String tempid){
        
        List<DevtFormMetadataEntity> crfFormMetadataEntityList= Lists.newArrayList(sysCrfFormMetadataDao.findAll());
        
        List<DevtFormMetadataEntity> sysCrfFormMetadataEntityList =  crfFormMetadataEntityList.stream().filter(crf-> crf.getId().equalsIgnoreCase(id)).collect(Collectors.toList());
        List<DevtFormMetadataEntity> patientEntityList =  crfFormMetadataEntityList.stream().filter(crf-> "父表".equalsIgnoreCase(crf.getTabletype()) && crf.getTempleid().equalsIgnoreCase(tempid)).collect(Collectors.toList());
        
        if (sysCrfFormMetadataEntityList.size()>0){
            if ("父表".equalsIgnoreCase(sysCrfFormMetadataEntityList.get(0).getTabletype()) || patientEntityList.size()>0){
                sysCrfFormMetadataEntityList.get(0).setTabletype("子表");
            }else {
                sysCrfFormMetadataEntityList.get(0).setTabletype("父表");
            }
//            sysCrfFormMetadataDao.save(sysCrfFormMetadataEntityList.get(0).getId(),sysCrfFormMetadataEntityList.get(0));
            sysCrfFormMetadataDao.save(sysCrfFormMetadataEntityList.get(0));
        }
        
        return Result.ok();
    }
}
